import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { CartList } from '../types/cart'

export const useCartStore = defineStore('cart',
	() => {
		const cartList = ref([] as CartList[])
		// 加入购物车	
		const addToCart = (goods : CartList) => {
			const filterList = cartList.value.find(item => item.proid === goods.proid)
			if (filterList) {
				filterList.num += goods.num
			} else {
				cartList.value.push(goods)
			}
		}

		// 更改商品选中状态
		const changeGoodsState = (goods : Partial<CartList>) => {
			const filterList = cartList.value.find(item => item.proid === goods.proid)
			if (filterList) return filterList.checked = goods.checked
		}

		// 更改商品数量
		const changeGoodsNum = (goods : Partial<CartList>) => {
			const filterList = cartList.value.find(item => item.proid === goods.proid)
			if (filterList) return filterList.num = goods.num
		}

		// 删除商品
		const delGoods = (proid) => {
			const filterList = cartList.value.filter(item => item.proid !== proid)
			cartList.value = filterList
		}

		// 全选正选
		const allSelect = computed(() => {
			return cartList.value.every(item => item.checked)
		})

		// 更改全部商品状态
		const changeAllSelect = (checked : boolean) => {
			return cartList.value.forEach(item => item.checked = checked)
		}

		// 计算勾选商品总价格
		const allCheckedPrice = computed(() => {
			return cartList.value.filter(item => item.checked).reduce((prev, item) => { return prev + item.num * item.price }, 0)
		})

		// 计算购物车总数量
		const allGoodsNum = computed(() => {
			return cartList.value.reduce((prev, item) => prev + item.num, 0)
		})

		return {
			cartList,
			addToCart,
			changeGoodsState,
			changeGoodsNum,
			delGoods,
			changeAllSelect,
			allSelect,
			allCheckedPrice,
			allGoodsNum
		}
	}, {
	persist: {
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value)
			},
			getItem(key) {
				return uni.getStorageSync(key)
			}
		}
	}
}
)